// 搭建服务
// 1、引入系统的http包，用于解析路径，启动http服务
// mysql数据库存储数据，mysql 8
// 数据库管理可视化工具 workbench navicat
let http = require("http")
let sql = require('./sql/sql')
let postData = require('./methods/postData')

let server = http.createServer(function (req, res) {
    // 设置服务器返回的数据开放
    res.setHeader("content-type", "application/json")
    // 设置服务器的数据开放
    res.setHeader("Access-Control-Allow-Origin", "*")
    res.setHeader("Access-Control-Allow-Headers", "*")
    res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS")
    if (req.url == "/comments") {
        sql('select * from hot_comments').then(result => {
            res.end(JSON.stringify(result))
        })

    }
    if (req.url == "/sendcomments") {
        postData(req, res).then(data => {
            let post_result = JSON.parse(data)
            sql(`insert into hot_comments(song_id,name,time,agree,comments) values
            ("${post_result.songID}","${post_result.name}","${post_result.time}","${post_result.agree}","${post_result.content}")`)
                .then(result => {
                    if (result.affectedRows == 1) {
                        res.end(JSON.stringify({ "status": 200 }))
                    }
                })
        })
    }
})
// 启动服务
server.listen('3003', function () { console.log("server is running"); })